package com.lupengning.es.test.search;

import java.io.IOException;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;

public class ESTest_doc_Search {

  public static void main(String[] args) throws IOException {
    RestHighLevelClient esClient = new RestHighLevelClient(
        RestClient.builder(new HttpHost("192.168.56.10", 9200, "http"))
    );

    //查询所有索引数据
    //查询所有索引数据(esClient);

    /**
     * 分组统计
     */
    //SearchByGroup(esClient);

    /**
     * 聚合查询（最大年龄）
     */
    //聚合查询(esClient);

    /**
     * Bool查询
     */
    //BoolSearch(esClient);

    SearchResponse response = esClient
        .search(new SearchRequest().indices("user").source(new SearchSourceBuilder()
                .query(QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("name", "zhangsan")))),
            RequestOptions.DEFAULT);

    esClient.close();
  }

  private static void BoolSearch(RestHighLevelClient esClient) throws IOException {
    SearchResponse response = esClient.search(new SearchRequest().indices("user")
            .source(new SearchSourceBuilder()
                .query(QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("age", 30)))),
        RequestOptions.DEFAULT);
  }

  private static void 聚合查询(RestHighLevelClient esClient) throws IOException {
    SearchResponse response = esClient.search(new SearchRequest().indices("user").source(
        new SearchSourceBuilder().aggregation(AggregationBuilders.max("MaxAge").field("age"))),
        RequestOptions.DEFAULT);
    for (SearchHit hit : response.getHits()) {
      //输出每条查询的结果信息
      System.out.println(hit.getSourceAsString());
    }
  }

  private static void SearchByGroup(RestHighLevelClient esClient) throws IOException {
    SearchResponse response = esClient
        .search(new SearchRequest().indices("user").source(new SearchSourceBuilder().aggregation(
            AggregationBuilders.terms("age_group").field("age"))), RequestOptions.DEFAULT);

    for (SearchHit hit : response.getHits()) {
      //输出每条查询的结果信息
      System.out.println(hit.getSourceAsString());
    }
  }

  private static void 查询所有索引数据(RestHighLevelClient esClient) throws IOException {
    SearchRequest request = new SearchRequest();
    request.indices("user");

    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
    sourceBuilder.query(QueryBuilders.matchAllQuery());
    request.source(sourceBuilder);

    SearchResponse response = esClient.search(request, RequestOptions.DEFAULT);

    SearchResponse response1 = esClient.search(new SearchRequest().indices("user")
            .source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery())
                .from(0).size(3)
                .sort("age",
                    SortOrder.ASC)
                .fetchSource(new String[]{"name", "age"}, new String[]{})),
        RequestOptions.DEFAULT);

    // 查询匹配
    SearchHits hits = response.getHits();
    System.out.println("took:" + response.getTook());
    System.out.println("timeout:" + response.isTimedOut());
    System.out.println("total:" + hits.getTotalHits());
    System.out.println("MaxScore:" + hits.getMaxScore());
    System.out.println("hits========>>");
    for (SearchHit hit : hits) {
      //输出每条查询的结果信息
      System.out.println(hit.getSourceAsString());
    }
    System.out.println("<<========");
  }
}
